<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="质检单号" prop="qualityCode">
        <el-input v-model="queryParams.qualityCode" placeholder="请输入质检单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="采购单号" prop="ordersNumber">
        <el-input v-model="queryParams.ordersNumber" placeholder="请输入采购订单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="质检方式" prop="inspectionType">
        <el-select v-model="queryParams.inspectionType" placeholder="请选择质检方式" clearable>
          <el-option v-for="dict in dict.type.tb_quality_inspection_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="质检员" prop="inspector">
        <el-input v-model="queryParams.inspector" placeholder="请输入质检员" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="质检状态" prop="inspectionStatus">
        <el-select v-model="queryParams.inspectionStatus" placeholder="请选择质检状态" clearable>
          <el-option v-for="dict in dict.type.tb_quality_inspection_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="质检时间">
        <el-date-picker v-model="daterangeInspectionDate" style="width: 240px" value-format="yyyy-MM-dd"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['depot:inspection:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['depot:inspection:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['depot:inspection:remove']">取消质检</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['depot:inspection:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange"
      style="width: 100%; overflow-x: auto;">
      <el-table-column type="selection" width="55" align="center" />

      <!-- 固定质检单号列到左侧 -->
      <el-table-column label="质检单号" align="center" prop="qualityCode" fixed="left" min-width="160" />

      <el-table-column label="采购订单号" align="center" prop="ordersNumber" min-width="160" />
      <el-table-column label="总质检量" align="center" prop="inspectionQuantity" min-width="120" />
      <el-table-column label="总次品量" align="center" prop="totalDefectiveQuantity" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.totalDefectiveQuantity || scope.row.totalDefectiveQuantity === 0 ?
            scope.row.totalDefectiveQuantity : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="总良品量" align="center" prop="totalPassQuantity" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.totalPassQuantity || scope.row.totalPassQuantity === 0 ? scope.row.totalPassQuantity : '-'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质检员" align="center" prop="inspector" min-width="120" />
      <el-table-column label="质检时间" align="center" prop="inspectionDate" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人" align="center" prop="consignee" min-width="120" />
      <el-table-column label="收货时间" align="center" prop="receiptTime" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiptTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购员" align="center" prop="userName" min-width="120" />
      <el-table-column label="质检状态" align="center" prop="inspectionStatus" min-width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tb_quality_inspection_status" :value="scope.row.inspectionStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 固定操作列到右侧 -->
      <el-table-column label="操作" align="center" fixed="right" min-width="180">
        <template slot-scope="scope">
          <el-dropdown size="mini" @command="command => handleCommand(command, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <!-- 完成质检 -->
              <el-dropdown-item v-if="scope.row.inspectionStatus == 0" command="handleCompleteInspection"
                icon="el-icon-edit" v-hasPermi="['depot:inspection:edit']">
                完成质检
              </el-dropdown-item>
              <!-- 取消质检 -->
              <el-dropdown-item v-if="scope.row.inspectionStatus == 0" command="handleDelete" icon="el-icon-delete"
                v-hasPermi="['depot:inspection:remove']">
                取消质检
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.inspectionStatus == 1" command="handleViewDetail" icon="el-icon-view"
                v-hasPermi="['depot:inspection:query']">
                详情
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改品检对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="质检单号" prop="qualityCode">
          <el-input v-model="form.qualityCode" placeholder="请输入质检单号" />
        </el-form-item>
        <el-form-item label="收货单ID" prop="receiptId">
          <el-input v-model="form.receiptId" placeholder="请输入收货单ID" />
        </el-form-item>
        <el-form-item label="采购订单号" prop="ordersId">
          <el-input v-model="form.ordersId" placeholder="请输入采购订单号" />
        </el-form-item>
        <el-form-item label="质检量" prop="inspectionQuantity">
          <el-input v-model="form.inspectionQuantity" placeholder="请输入质检量" />
        </el-form-item>
        <el-form-item label="质检方式" prop="inspectionType">
          <el-select v-model="form.inspectionType" placeholder="请选择质检方式">
            <el-option v-for="dict in dict.type.tb_quality_inspection_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抽检比例" prop="samplingRatio">
          <el-input v-model="form.samplingRatio" placeholder="请输入抽检比例" />
        </el-form-item>
        <el-form-item label="抽检数量" prop="samplingQuantity">
          <el-input v-model="form.samplingQuantity" placeholder="请输入抽检数量" />
        </el-form-item>
        <el-form-item label="抽检合格率" prop="samplingPassRate">
          <el-input v-model="form.samplingPassRate" placeholder="请输入抽检合格率" />
        </el-form-item>
        <el-form-item label="总次品量" prop="totalDefectiveQuantity">
          <el-input v-model="form.totalDefectiveQuantity" placeholder="请输入总次品量" />
        </el-form-item>
        <el-form-item label="总良品量" prop="totalPassQuantity">
          <el-input v-model="form.totalPassQuantity" placeholder="请输入总良品量" />
        </el-form-item>
        <el-form-item label="质检员" prop="inspector">
          <el-input v-model="form.inspector" placeholder="请输入质检员" />
        </el-form-item>
        <el-form-item label="质检时间" prop="inspectionDate">
          <el-date-picker clearable v-model="form.inspectionDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择质检时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="质检状态" prop="inspectionStatus">
          <el-select v-model="form.inspectionStatus" placeholder="请选择质检状态">
            <el-option v-for="dict in dict.type.tb_quality_inspection_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 完成质检弹窗 -->
    <el-dialog :title="title" :visible.sync="inspectionOpen" :width="dialogWidth" append-to-body>
      <!-- 质检信息表单 -->
      <el-form :model="form" label-width="80px" :rules="rules" ref="inspectionForm">
        <el-row>
          <el-col :span="6">
            <el-form-item label="质检单号" prop="qualityCode">
              <el-input v-model="form.qualityCode" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购单号" prop="ordersNumber">
              <el-input v-model="form.ordersNumber" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="总质检量" prop="inspectionQuantity">
              <el-input v-model="form.inspectionQuantity" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检员" prop="inspector">
              <el-input v-model="form.inspector" :disabled="isView" placeholder="请输入质检员" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="质检时间" prop="inspectionDate">
              <el-date-picker v-model="form.inspectionDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择质检时间"
                :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 产品质检详情窗口 -->
      <el-table :data="goodsList" style="width: 100%" border show-summary :summary-method="getSummaries">
        <el-table-column prop="productName" label="产品名称" min-width="120" />
        <el-table-column prop="sku" label="sku" min-width="100" />
        <el-table-column label="GTIN" align="center" min-width="120">
          <template slot-scope="childScope">
            <div v-if="childScope.row.gtins && childScope.row.gtins.length">
              <div v-for="(gtin, index) in childScope.row.gtins" :key="index">{{ gtin }}</div>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>

        <el-table-column prop="inspectedQuantity" label="质检数量" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.inspectedQuantity }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="inspectionType" label="质检方式" min-width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.inspectionType" placeholder="请选择" size="mini" :disabled="isView"
              @change="handleInspectionTypeChange(scope.row)">
              <el-option v-for="dict in dict.type.tb_quality_inspection_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>

        <!-- 抽检量 -->
        <el-table-column label="抽检量" min-width="100">
          <template slot-scope="scope">
            <el-input v-if="scope.row.inspectionType === '0'" v-model="scope.row.samplingQuantity" size="mini"
              @input="handleSamplingQuantityInput(scope.row)" :disabled="isView" />
            <span v-else> - </span>
          </template>
        </el-table-column>

        <!-- 抽检次品量 -->
        <el-table-column label="抽检次品量" min-width="100">
          <template slot-scope="scope">
            <el-input v-if="scope.row.inspectionType === '0'" v-model="scope.row.defectiveQuantity" size="mini"
              @input="handleDefectiveQuantityInput(scope.row)" :disabled="isView" />
            <span v-else> - </span>
          </template>
        </el-table-column>

        <!-- 良品量 -->
        <el-table-column prop="passQuantity" label="良品量" min-width="100">
          <template slot-scope="scope">
            <!-- 抽检方式显示计算值，全检方式允许输入 -->
            <span v-if="scope.row.inspectionType === '0'">{{ scope.row.passQuantity }}</span>
            <el-input v-else-if="scope.row.inspectionType === '1'" v-model="scope.row.passQuantity" size="mini"
              @input="handlePassQuantityInput(scope.row)" :disabled="isView" />
            <span v-else-if="scope.row.inspectionType === '2'"> {{ scope.row.inspectedQuantity }} </span>
            <span v-else> - </span>
          </template>
        </el-table-column>

        <!-- 次品量 -->
        <el-table-column prop="defectiveQuantity" label="次品量" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.inspectionType === '1'">{{ scope.row.defectiveQuantity }}</span>
            <span v-else-if="scope.row.inspectionType === '0'">{{ scope.row.defectiveQuantity }}</span>
            <span v-else-if="scope.row.inspectionType === '2'"> 0 </span>
            <span v-else> - </span>
          </template>
        </el-table-column>

        <!-- 未质检量 -->
        <!-- <el-table-column label="未质检量" min-width="100">
          <template slot-scope="scope">
            <el-input v-if="scope.row.inspectionType === '1'" v-model="scope.row.uninspectedQuantity" size="mini"
              @input="handleUninspectedQuantityInput(scope.row)" />
            <span v-else> - </span>
          </template>
        </el-table-column> -->

        <!-- 抽检合格率 -->
        <el-table-column label="抽检合格率" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.inspectionType === '0'">{{ computeSamplingPassRate(scope.row) }}</span>
            <span v-else> - </span>
          </template>
        </el-table-column>

        <!-- 抽检比例 -->
        <el-table-column label="抽检比例" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.inspectionType === '0'">{{ computeSamplingRatio(scope.row) }}</span>
            <span v-else> - </span>
          </template>
        </el-table-column>

        <!-- 备注列 -->
        <el-table-column label="备注" min-width="120">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="mini" :disabled="isView" placeholder="请输入备注" />
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="100">
          <template slot-scope="scope">
            <!-- 打印按钮 -->
            <el-button type="text" @click="handlePrint(scope.row)">打印</el-button>
            <el-button type="text" @click="handleViewQualityItems(scope.row)">查看质检项</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isView" type="primary" @click="submitInspectionForm" :loading="loading">确 定</el-button>
        <el-button @click="inspectionOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打印弹窗 -->
    <el-dialog :visible.sync="printDialogVisible" title="打印" width="500px" @close="printDialogVisible = false">
      <!-- 打印内容 -->
      <printPage ref="printPage" :sku="selectedSku" :productName="myProductName"></printPage>
      <div slot="footer" class="dialog-footer">
        <el-button @click="printDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrintAction">打印</el-button>
      </div>
    </el-dialog>

    <!-- 质检项详情窗口 -->
    <el-dialog title="质检项详情" :visible.sync="qualityItemDialogVisible" width="40%" append-to-body>
      <el-table :data="selectedQualityItems" class="full-width-table" border empty-text="该商品暂无质检项">
        <el-table-column label="质检项（最多30项）" prop="checkItem" min-width="200">
          <template #default="{ row }">
            <span>{{ row.checkItem }}</span>
          </template>
        </el-table-column>
        <el-table-column label="质检内容" prop="checkContent" min-width="400">
          <template #default="{ row }">
            <span>{{ row.checkContent }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 图片展示部分 -->
      <div v-if="imagesPath.length" class="image-gallery" style="margin-top: 30px;">
        <image-upload ref="productImageUpload" :auto-upload="false" v-model="imagesPath" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qualityItemDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listInspection, getInspection, delInspection, addInspection, updateInspection } from "@/api/depot/inspection";
import PrintPage from '@/components/PrintPage';
export default {
  name: "Inspection",
  dicts: ['tb_quality_inspection_type', 'tb_quality_inspection_status'],
  components: {
    PrintPage,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 保存选中的行的状态数据
      selectedRows: [],
      qualityCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品检表格数据
      inspectionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 质检状态(0：质检中  1：已质检   2：已质检时间范围
      daterangeInspectionDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qualityCode: null,
        ordersId: null,
        ordersNumber: null,
        inspectionType: null,
        inspector: null,
        inspectionDate: null,
        inspectionStatus: null,
      },
      // 表单参数
      form: {
        totalDefectiveQuantity: 0,
        totalPassQuantity: 0,
      },
      // 表单校验
      rules: {
        inspector: [{ required: true, message: "请输入质检员", trigger: "blur" }],
        inspectionDate: [
          { required: true, message: "请选择质检时间", trigger: "change" }
        ]
      },
      dialogWidth: '1300px', // 默认宽度
      goodsList: [],        // 质检商品列表
      inspectionOpen: false, //完成质检弹窗控制
      isView: false, // 标识当前是否为详情模式
      qualityItemDialogVisible: false, // 控制质检项弹窗的显示状态
      selectedQualityItems: [], // 存储当前选择的产品质检项
      imagesPath: [],
      // --------- 打印开始----------
      selectedSku: '', // 存储当前选中行的 SKU
      myProductName: '', // 存储当前行选中的产品名称
      printDialogVisible: false, // 控制打印弹窗的显示
      // --------- 打印结束----------
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询品检列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeInspectionDate && '' != this.daterangeInspectionDate) {
        this.queryParams.params["beginInspectionDate"] = this.daterangeInspectionDate[0];
        this.queryParams.params["endInspectionDate"] = this.daterangeInspectionDate[1];
      }
      listInspection(this.queryParams).then(response => {
        this.inspectionList = response.rows.sort((a, b) => a.inspectionStatus - b.inspectionStatus);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inspectionId: null,
        qualityCode: null,
        receiptId: null,
        ordersId: null,
        inspectionQuantity: null,
        inspectionType: null,
        samplingRatio: null,
        samplingQuantity: null,
        samplingPassRate: null,
        totalDefectiveQuantity: null,
        totalPassQuantity: null,
        inspector: null,
        inspectionDate: null,
        inspectionStatus: null,
        createTime: null,
        updateTime: null,
        totalDefectiveQuantity: 0,
        totalPassQuantity: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeInspectionDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inspectionId)
      this.selectedRows = selection.map(item => item.inspectionStatus);
      this.qualityCodes = selection.map(item => item.qualityCode);
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品检";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inspectionId = row.inspectionId || this.ids
      getInspection(inspectionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改品检";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inspectionId != null) {
            updateInspection(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInspection(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    async handleDelete(row = null) {
      let inspectionIds;
      // 如果是勾选操作
      const allCheckedAreOne = this.selectedRows.every(item => item == '0');

      if (!allCheckedAreOne) {
        this.$message.error("只能取消质检中的质检单！");
        return;
      }
      // 如果是单行操作
      if (row.inspectionStatus == 1 || row.inspectionStatus == 2 || row.inspectionStatus == 3) {
        this.$message.error("只能取消质检中的质检单！");
        return;
      }
      inspectionIds = row.inspectionId || this.ids;

      let qualityCode = [];
      if (row.qualityCode) {
        qualityCode.push(row.qualityCode)
      } else {
        qualityCode = [...this.qualityCodes]
      }
      // qualityCode = row.qualityCode || [...this.qualityCodes];

      try {
        await this.$modal.confirm(`是否取消品检编号为"${qualityCode.join(', ')}"的数据项？`);

        await delInspection(inspectionIds);

        this.getList();
        this.$modal.msgSuccess("取消成功");
      } catch (error) {
        if (error && error !== 'cancel') {
          console.error("Deletion failed:", error);
          this.$message.error("操作取消或网络请求失败");
        }
      }
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('depot/inspection/export', {
        ...this.queryParams
      }, `inspection_${new Date().getTime()}.xlsx`)
    },
    handleCommand(command, row) {
      if (command === 'handleCompleteInspection') {
        this.handleCompleteInspection(row);
      } else if (command === 'handleDelete') {
        this.handleDelete(row);
      } else if (command === 'handleViewDetail') {
        this.handleViewDetail(row);
      }
    },
    // 详情打开弹窗
    handleViewDetail(row) {
      this.reset();
      const inspectionId = row.inspectionId;
      getInspection(inspectionId).then(response => {
        this.form = response.data;
        this.goodsList = response.data.inspectionDetails || [];
        this.inspectionOpen = true;
        this.isView = true; // 设置为详情模式
        this.title = "质检详情";
        this.dialogWidth = "90%";
      });
      this.computeTotals();
    },
    handleInspectionTypeChange(row) {
      // 清空所有与质检方式相关的字段
      row.samplingQuantity = null;
      row.defectiveQuantity = null;
      row.passQuantity = null;
      row.defectiveQuantity = null;
      row.samplingPassRate = null;
      row.samplingRatio = null;
      row.uninspectedQuantity = null;
      if(row.inspectionType == '2'){
        // 当质检方式为2的时候将质检量赋值给良品量，次品量赋值为0
        row.passQuantity = row.inspectedQuantity;
        row.defectiveQuantity = 0;
      }
      // 调用 computeTotals 方法计算总计值
      this.computeTotals();
    },
    handleCompleteInspection(row) {
      this.reset();
      const inspectionId = row.inspectionId;
      getInspection(inspectionId).then(response => {
        this.form = response.data;
        // 确保正确获取 inspectionDetails
        this.goodsList = response.data.inspectionDetails || [];
        // 初始化每个商品的相关字段
        this.goodsList.forEach(item => {
          item.samplingQuantity = item.samplingQuantity || null;
          item.defectiveQuantity = item.defectiveQuantity || null;
          item.passQuantity = item.passQuantity || null;
          item.samplingPassRate = item.samplingPassRate || null;
          item.samplingRatio = item.samplingRatio || null;
        });
        this.isView = false; // 设置为完成质检模式
        this.inspectionOpen = true;
        this.title = "完成质检";
        this.dialogWidth = "90%"; // 调整弹窗宽度
      });
      this.computeTotals();
    },
    // 处理抽检量输入
    handleSamplingQuantityInput(row) {
      const samplingQuantity = Number(row.samplingQuantity);
      const inspectedQuantity = Number(row.inspectedQuantity);

      if (samplingQuantity > inspectedQuantity) {
        row.samplingQuantity = inspectedQuantity;
      }
      this.updateCalculations(row);
    },
    // 处理抽检次品量输入
    handleDefectiveQuantityInput(row) {
      const defectiveQuantity = Number(row.defectiveQuantity);
      const samplingQuantity = Number(row.samplingQuantity);

      if (defectiveQuantity > samplingQuantity) {
        row.defectiveQuantity = samplingQuantity;
      }
      this.updateCalculations(row);
    },
    // 处理总良品量输入（全检）
    handlePassQuantityInput(row) {
      const passQuantity = Number(row.passQuantity);
      const inspectedQuantity = Number(row.inspectedQuantity);
      const uninspectedQuantity = Number(row.uninspectedQuantity) || 0;

      if (passQuantity + uninspectedQuantity > inspectedQuantity) {
        row.passQuantity = inspectedQuantity - uninspectedQuantity;
      }
      this.updateCalculations(row);
    },
    // 处理未质检量输入（全检）
    // handleUninspectedQuantityInput(row) {
    //   const uninspectedQuantity = Number(row.uninspectedQuantity);
    //   const inspectedQuantity = Number(row.inspectedQuantity);
    //   const passQuantity = Number(row.passQuantity) || 0;

    //   if (uninspectedQuantity + passQuantity > inspectedQuantity) {
    //     row.uninspectedQuantity = inspectedQuantity - passQuantity;
    //   }
    //   this.updateCalculations(row);
    // },
    // 更新计算结果
    updateCalculations(row) {
      const inspectionType = row.inspectionType;
      const inspectedQuantity = Number(row.inspectedQuantity);

      if (inspectionType === "0") {
        // 抽检
        const samplingQuantity = Number(row.samplingQuantity);
        const defectiveQuantity = Number(row.defectiveQuantity);

        // 校验抽检量不超过质检数量
        if (samplingQuantity > inspectedQuantity) {
          row.samplingQuantity = inspectedQuantity;
        }

        // 校验次品量不超过抽检量
        if (defectiveQuantity > samplingQuantity) {
          row.defectiveQuantity = samplingQuantity;
        }

        // 次品量 = 抽检次品量
        row.defectiveQuantity = defectiveQuantity;

        // 良品量 = 质检数量 - 抽检次品量
        row.passQuantity = inspectedQuantity - defectiveQuantity;

        // 抽检合格率 = (抽检量 - 抽检次品量) / 抽检量 * 100
        row.samplingPassRate = ((samplingQuantity - defectiveQuantity) / samplingQuantity * 100).toFixed(2);

        // 抽检比例 = 抽检量 / 质检数量 * 100
        row.samplingRatio = ((samplingQuantity / inspectedQuantity) * 100).toFixed(2);
      } else if (inspectionType === "1") {
        // 全检
        const passQuantity = Number(row.passQuantity);

        // 校验良品量不超过质检数量
        if (passQuantity > inspectedQuantity) {
          row.passQuantity = inspectedQuantity;
        }

        // 次品量 = 质检数量 - 良品量
        row.defectiveQuantity = inspectedQuantity - passQuantity;

        if (row.defectiveQuantity < 0) {
          row.defectiveQuantity = 0;
        }

        // 抽检量（全检下等于质检数量）
        row.samplingQuantity = inspectedQuantity;

        // 抽检合格率 = 良品量 / 质检数量 * 100
        if (inspectedQuantity > 0) {
          row.samplingPassRate = ((passQuantity / inspectedQuantity) * 100).toFixed(2);
        } else {
          row.samplingPassRate = "0.00";
        }

        // 抽检比例 = 100%
        row.samplingRatio = "100.00";
      }

      // 调用 computeTotals 方法计算总计值
      this.computeTotals();
    },
    // 计算抽检合格率显示
    computeSamplingPassRate(row) {
      if (row.samplingPassRate) {
        return row.samplingPassRate + "%";
      }
      return "-";
    },
    // 计算抽检比例显示
    computeSamplingRatio(row) {
      if (row.samplingRatio) {
        return row.samplingRatio + "%";
      }
      return "-";
    },
    // 提交质检表单
    async submitInspectionForm() {
      this.loading = true;
      // 校验表单
      this.$refs["inspectionForm"].validate(async (valid) => {
        if (!valid) {
          return; // 如果表单校验未通过，直接返回
        }

        // 校验每个商品的质检数据
        const validDetails = this.validateInspectionDetails();
        if (!validDetails) return; // 如果商品校验未通过，直接返回

        // 准备提交数据
        const inspectionData = {
          ...this.form,
          inspectionDetails: this.goodsList,
        };

        try {
          const response = await updateInspection(inspectionData);

          // 检查请求响应
          if (response.code === 200) {
            this.$message.success("质检完成");
            this.inspectionOpen = false;
            this.loading = false;
            this.getList(); // 刷新列表数据
          } else {
            this.$message.error(response.message || "质检提交失败，请稍后再试");
          }
        } catch (error) {
          console.error("Error submitting inspection data:", error);
          this.$message.error("网络请求失败，请稍后再试");
        }
      });
    },

    // 分离质检详情校验逻辑
    validateInspectionDetails() {
      for (const item of this.goodsList) {
        const inspectedQuantity = Number(item.inspectedQuantity);

        // 校验质检方式
        if (!item.inspectionType) {
          this.$message.error(`请为产品 "${item.productName}" 选择质检方式`);
          return false;
        }

        if (item.inspectionType === "0") {
          // 抽检
          if (!item.samplingQuantity || item.samplingQuantity <= 0) {
            this.$message.error(`请填写产品 "${item.productName}" 的抽检量`);
            return false;
          }
          if (item.defectiveQuantity === null || item.defectiveQuantity < 0) {
            this.$message.error(`请填写产品 "${item.productName}" 的抽检次品量`);
            return false;
          }
          if (Number(item.samplingQuantity) > inspectedQuantity) {
            this.$message.error(`产品 "${item.productName}" 的抽检量不能超过质检数量`);
            return false;
          }
          if (Number(item.defectiveQuantity) > Number(item.samplingQuantity)) {
            this.$message.error(`产品 "${item.productName}" 的抽检次品量不能超过抽检量`);
            return false;
          }
        } else if (item.inspectionType === "1") {
          // 全检
          if (item.passQuantity === null || item.passQuantity < 0 || item.passQuantity === '') {
            this.$message.error(`请填写产品 "${item.productName}" 的良品量`);
            return false;
          }
          if (Number(item.passQuantity) > inspectedQuantity) {
            this.$message.error(`产品 "${item.productName}" 的良品量不能超过质检数量`);
            return false;
          }
          const totalQuantity = Number(item.passQuantity) + Number(item.defectiveQuantity);
          if (totalQuantity !== inspectedQuantity) {
            this.$message.error(
              `产品 "${item.productName}" 的良品量和次品量之和必须等于质检数量`
            );
            return false;
          }
        }
      }
      return true; // 如果所有校验都通过，返回 true
    },
    computeTotals() {
      let totalDefective = 0;
      let totalPass = 0;
      this.goodsList.forEach(item => {
        totalDefective += Number(item.defectiveQuantity) || 0;
        totalPass += Number(item.passQuantity) || 0;
      });
      this.form.totalDefectiveQuantity = totalDefective;
      this.form.totalPassQuantity = totalPass;
    },
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const field = column.property;
        if (field === 'defectiveQuantity') {
          sums[index] = this.form.totalDefectiveQuantity;
        } else if (field === 'passQuantity') {
          sums[index] = this.form.totalPassQuantity;
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    // 查看质检项按钮点击事件
    handleViewQualityItems(row) {
      // 模拟从当前产品数据中提取质检项
      if (row.qualityItems) {
        this.selectedQualityItems = row.qualityItems;
      } else {
        this.selectedQualityItems = [];
      }

      if (row.imagesPath) {
        this.imagesPath = row.imagesPath;
      } else {
        this.imagesPath = row.imagesPath;
      }
      this.qualityItemDialogVisible = true;
    },
    // 打印按钮点击事件
    handlePrint(row) {
      // 获取当前行的 sku 并更新 selectedSku
      this.selectedSku = row.sku;
      this.myProductName = row.productName;
      // 显示打印弹窗
      this.printDialogVisible = true;
    },
    // 弹窗内的打印按钮点击事件
    handlePrintAction() {
      // 调用 PrintPage 组件中的 printPage 方法进行打印
      this.$nextTick(() => {
        this.$refs.printPage.printPage(); // 调用 PrintPage 组件的打印方法
      });
    },
  }
};
</script>
<style scoped>
/* 可以设置表格外观的样式 */
.el-table__body-wrapper {
  overflow-x: auto;
  /* 确保表格可以横向滚动 */
}
</style>
